#!/usr/bin/env python
# coding: utf-8
import web
from config import settings,util
from config.settings import session
from datetime import datetime
import sys,os,shutil
import ConfigParser
import authbase

db = settings.db
render_login = web.template.render('templates/')
render = settings.render
tb="alarms"
class Index(authbase.AuthBase):
    def GET(self):
        alarms = db.select(tb)
        return render.alarms.index(alarms=alarms)

def get_by_id(id):
    try:
        return db.select(tb, where = 'id=$id', vars = locals())[0]
    except IndexError:
        return None


class New(authbase.AuthBase):
    def GET(self):
        new_alarm=""
        return render.alarms.new(new_alarm="",data_type_title_dict=util.invert_dict(util.data_type_title_dict))

class Create(authbase.AuthBase):
    def POST(self):
        i = web.input()
        field_name = i.get('name', None)
        if not field_name:
            return render.error('名称不能为空', None)
        name=util.data_type_title_dict[field_name]
        max_value = i.get('max_value', None)
        if not max_value:
            return render.error('最大值不能为空', None)
        state = i.get('state', False)

        db.insert(tb,field_name=field_name, name=name,max_value=max_value,state=state)
        raise web.seeother('/alarms')


class Edit(authbase.AuthBase):
    def GET(self, id):
        alarm = get_by_id(int(id))
        if not alarm:
            return render.error('没找到这条记录', None)
        return render.alarms.edit(new_alarm=alarm,data_type_title_dict=util.invert_dict(util.data_type_title_dict))

    def POST(self, id):
        alarm = get_by_id(int(id))
        if not alarm:
            return render.error('没找到这条记录', None)
        i = web.input()
        field_name = i.get('name', None)
        if not field_name:
            return render.error('名称不能为空', None)
        name=util.data_type_title_dict[field_name]
        max_value = i.get('max_value', None)
        if not max_value:
            return render.error('最大值不能为空', None)
        state = i.get('state', False)
        
        db.update(tb, field_name=field_name, name=name,max_value=max_value,state=state, where='id=$id', vars=locals())
        return render.error('编辑成功！', '/alarms')

class Delete(authbase.AuthBase):
    def GET(self, id):
        alarm = get_by_id(int(id))
        if not alarm:
            return render.error('没找到这条记录', None)
        db.delete(tb, where='id=$id', vars=locals())
        return render.error('删除成功！', '/alarms')
